let date = new Date()
//获取今年年份
let year = date.getFullYear()
//获取当月
let month = date.getMonth()

let yearEl = document.querySelector('.year')
let monthEl = document.querySelector('.month')

setYearSelect()
setMonthSelect()
/* 每日统计的切换 */
let chooseList1 = document.querySelectorAll('.dailyStatistics .choose .item')
let chooseBtn1 = document.querySelector('.dailyStatistics .choose')

/* 分类报表的切换 */
let chooseList2 = document.querySelectorAll('.classifiedStatement .choose .item')
let chooseBtn2 = document.querySelector('.classifiedStatement .choose')
// chooseOne(chooseList2, chooseBtn2)

//年份选择框
function setYearSelect() {
  for (let i = -10; i < 11; i++) {
    let option = new Option(year + i, year + i)
    yearEl.appendChild(option)
  }

  yearEl.value = year
}

//月份选择框
function setMonthSelect() {
  for (let i = 0; i < 12; i++) {
    let option = new Option(`${i + 1}月`, i)

    monthEl.appendChild(option)
  }

  monthEl.value = month
}



/* 收支总览的柱状图 */
function bar(time, amount) {
  //1.创建实例对象
  let myChart = echarts.init(document.querySelector('.dailyStatistics .bar'))
  //2.指定配置项和数据
  let option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'none'
      },
      triggerOn: "click",
      position: "lef",
    },
    title: {
      text: "每日统计",
      textStyle: {
        color: "#333",
        fontWeight: "normal",
        fontSize: "20",
      },
      left: "center"
    },
    //修改图表大小
    grid: {
      left: '0%',
      right: '4%',
      bottom: '0%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: time,
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          color: "#999",
          interval: 0,
          fontSize: "12"
        },
        axisTick: {
          show: false
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        }
      },
    ],
    series: [
      {
        name: '支出',
        type: 'bar',
        barWidth: '30%',
        itemStyle: {
          //修改柱子圆角
          barBorderRadius: [20, 20, 0, 0],
        },
        data: amount
      }
    ]
  };
  //3.把配置项给实例对象
  myChart.setOption(option)
}

/*每日统计 点击切换 */
function chooseOne1(chooseList, chooseBtn, expenditureTime, expenditureAmount, incomeTime, incomeAmount, allTime, allAmount) {

  //判断
  let isChoose = false
  chooseBtn.onclick = function (e) {

    for (let j = 0; j < chooseList.length; j++) {
      if (e.target == chooseList[j]) {
        isChoose = true
      }
    }
    if (isChoose) {
      for (let i = 0; i < chooseList.length; i++) {
        chooseList[i].classList.remove('active')
      }
      e.target.classList.add('active')
      isChoose = false
      if (e.target.textContent === '支出') {
        bar(expenditureTime, expenditureAmount)
      } else if (e.target.textContent === '收入') {
        bar(incomeTime, incomeAmount)
      } else {
        bar(allTime, allAmount)
      }
    }
  }
}

//分类报表 点击切换
function chooseOne2(chooseList, chooseBtn, pieData1, pieColor1, pieData2, pieColor2,) {

  //判断
  let isChoose = false
  chooseBtn.onclick = function (e) {

    for (let j = 0; j < chooseList.length; j++) {
      if (e.target == chooseList[j]) {
        isChoose = true
      }
    }
    if (isChoose) {
      for (let i = 0; i < chooseList.length; i++) {
        chooseList[i].classList.remove('active')
      }
      e.target.classList.add('active')
      isChoose = false
      // console.log(e.target.textContent)
      if (e.target.textContent === '支出') {
        pie(pieData1, pieColor1)
      } else {
        pie(pieData2, pieColor2)
      }
    }
  }
}


/* 分类报表的饼状图 */
function pie(pieData, color) {
  let myChart = echarts.init(document.querySelector('.classifiedStatement .pie'))
  let option = {
    color: color,
    title: {
      text: "支出比例",
      left: "center",
      top: "center",
      textStyle: {
        fontWeight: 'normal',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '60%'],

        /* emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
            formatter(param) {
              // correct the percentage
              return param.name + ' (' + param.percent * 2 + '%)';
            }
          }
        }, */
        label: {
          formatter: `{b}: {d}%`,
          fontSize: 10
        },
        labelLine: {
          show: true,
          length: 8,
          length2: 6
        },
        data: pieData
      }
    ]
  };
  myChart.setOption(option)
}



let monthParameter = Number(monthEl.value) + 1
let yearParameter = Number(yearEl.value)


//支出数据
let expenditureDate = []

//收入数据
let incomeDate = []
//全部数据
let allDate = []

getMonthDate(yearParameter, monthParameter)
//获取月份数据
async function getMonthDate(yearParameter, monthParameter) {



  let monthDate = await getData(yearParameter, monthParameter)
  // console.log(monthDate)
  incomeDate = []
  expenditureDate = []
  allDate = []


  for (let j = 0; j < monthDate.length; j++) {
    if (monthDate[j].moneyType && !monthDate[j].isReimbursed) {
      incomeDate.push(monthDate[j])
    } else if (!monthDate[j].moneyType && !monthDate[j].isReimbursed) {
      expenditureDate.push(monthDate[j])
    }

  }

  for (let i = 0; i < monthDate.length; i++) {
    if (!monthDate[i].isReimbursed) {
      allDate.push(monthDate[i])
    }
  }
  // console.log(incomeDate)
  // console.log(expenditureDate)
  // console.log(allDate)

  //收支总览
  summaryUpdate(allDate)

  //每日统计
  dailyStatisticsUpdate()

  //分类报表
  classifiedStatementUpdate()


  //日报表
  dailyStatementUpdate()

}

//计算lastDateNumber
function calcInfo(year, month) {
  let time = new Date(year, month)

  time.setMonth(Number(month) + 1)
  time.setDate(0)
  let lastDateNumber = time.getDate()

  return lastDateNumber
}


//补零
function addZero(m) {
  return m < 10 ? '0' + m : m
}

//时间戳转化为具体日期
function format(timeStamp) {
  let time = new Date(timeStamp);
  let y = time.getFullYear();
  let m = time.getMonth() + 1;
  let d = time.getDate();
  return y + '-' + addZero(m) + '-' + addZero(d);
}
//将月日取出
function formatDate(time) {
  let time1 = format(time)
  let time2 = time1.split('-')
  time2.shift()
  return time2.join('-')
}

//柱状图数据合并
function dataMerging(timer, amount, data) {
  for (let i = 0; i < data.length; i++) {
    let time = formatDate(data[i].time)
    if (timer.indexOf(time) === -1) {
      timer.unshift(time)
    }
  }
  for (let i = 0; i < timer.length; i++) {
    amount.unshift(0)
  }
  for (let i = 0; i < data.length; i++) {
    let time = formatDate(data[i].time)
    if (timer.indexOf(time) !== -1) {
      let index = timer.indexOf(time)
      amount[index] += Number(data[i].money)
    }
  }
}

//收支总览更新
function summaryUpdate(allDate) {
  let expenditure = 0
  let income = 0
  let balance = 0
  let average = 0
  //当月天数
  let lastDateNumber = calcInfo(yearParameter, monthParameter - 1)
  for (let i = 0; i < allDate.length; i++) {
    if (allDate[i].moneyType) {
      income += Number(allDate[i].money)
    } else {
      expenditure += Number(allDate[i].money)
    }
  }
  balance = income - expenditure
  // console.log(expenditure, lastDateNumber)
  average = (expenditure / lastDateNumber).toFixed(2)

  document.querySelector('.summary .expenditure .number').textContent = expenditure
  document.querySelector('.summary .income .number').textContent = income
  document.querySelector('.summary .balance .number').textContent = balance
  document.querySelector('.summary .averageDailyExpenditure .number').textContent = average
}

//每日统计更新
function dailyStatisticsUpdate() {
  //支出柱形图数据
  let expenditureTime = []
  let expenditureAmount = []
  dataMerging(expenditureTime, expenditureAmount, expenditureDate)

  //收入柱形图数据
  let incomeTime = []
  let incomeAmount = []
  dataMerging(incomeTime, incomeAmount, incomeDate)

  //全部柱形图数据
  let allTime = []
  let allAmount = []
  dataMerging(allTime, allAmount, allDate)

  bar(expenditureTime, expenditureAmount)
  chooseOne1(chooseList1, chooseBtn1, expenditureTime, expenditureAmount, incomeTime, incomeAmount, allTime, allAmount)
}

//饼图数据合并
async function pieMerging(color, amount, type, data, pieData) {
  for (let i = 0; i < data.length; i++) {
    if (type.indexOf(data[i].consumeType) === -1) {
      type.unshift(data[i].consumeType)
    }
  }
  for (let i = 0; i < type.length; i++) {
    amount.unshift(0)
  }
  for (let i = 0; i < data.length; i++) {
    if (type.indexOf(data[i].consumeType) !== -1) {
      let index = type.indexOf(data[i].consumeType)
      amount[index] += Number(data[i].money)
    }
  }
  // console.log(amount)
  // console.log(type)
  for (let i = 0; i < type.length; i++) {
    color.unshift(await getConsumeColor(type[i]))
  }
  // console.log(color)
  for (let i = 0; i < type.length; i++) {
    let object = {
      value: amount[i], name: type[i]
    }
    pieData.push(object)
  }
  return {
    color, pieData
  }
}

//分类报表更新
async function classifiedStatementUpdate() {
  //支出类型
  let expenditureType = []
  //支出颜色
  let expenditureColor = []
  //支出金额
  let expenditureAmount = []
  //饼状图数据
  let pie1 = []

  let { color: pieColor1, pieData: pieData1 } = await pieMerging(expenditureColor, expenditureAmount, expenditureType, expenditureDate, pie1)
  // console.log(pieColor1, pieData1)


  //收入类型
  let incomeType = []
  //收入颜色
  let incomeColor = []
  //收入金额
  let incomeAmount = []
  //饼状图数据
  let pie2 = []
  let { color: pieColor2, pieData: pieData2 } = await pieMerging(incomeColor, incomeAmount, incomeType, incomeDate, pie2)
  // console.log(pieColor2, pieData2)

  pie(pieData1, pieColor1)
  //分类报表的切换
  chooseOne2(chooseList2, chooseBtn2, pieData1, pieColor1, pieData2, pieColor2)
}

//日报表更新
function dailyStatementUpdate() {
  let date = []
  let income = []
  let expenditure = []
  let balance = []

  //获取date数据
  for (let i = 0; i < allDate.length; i++) {
    let time = formatDate(allDate[i].time)
    if (date.indexOf(time) === -1) {
      date.unshift(time)
    }
  }
  for (let i = 0; i < date.length; i++) {
    income.unshift(0)
    expenditure.unshift(0)
    balance.unshift(0)
  }
  //获取income数据
  for (let i = 0; i < incomeDate.length; i++) {
    let time = formatDate(incomeDate[i].time)
    if (date.indexOf(time) !== -1) {
      let index = date.indexOf(time)
      income[index] += Number(incomeDate[i].money)
    }
  }
  //获取expenditure数据
  for (let i = 0; i < expenditureDate.length; i++) {
    let time = formatDate(expenditureDate[i].time)
    if (date.indexOf(time) !== -1) {
      let index = date.indexOf(time)
      expenditure[index] += Number(expenditureDate[i].money)
    }
  }
  //获取balance数据
  for (let i = 0; i < date.length; i++) {
    balance[i] = income[i] - expenditure[i]
  }

  let html = ``
  for (let i = 0; i < date.length; i++) {
    html += `<div class="item">
    <div class="date">${date[i]}</div>
    <div class="income">${income[i]}</div>
    <div class="expenditure">${expenditure[i]}</div>
    <div class="balance">${balance[i]}</div>
  </div>`
  }

  document.querySelector('.dailyStatement .table .tbody').innerHTML = html
}

//月变化
monthEl.onchange = function () {
  let month = Number(monthEl.value) + 1
  let year = Number(yearEl.value)

  getMonthDate(year, month)
}
yearEl.onchange = function () {
  let month = Number(monthEl.value) + 1
  let year = Number(yearEl.value)

  getMonthDate(year, month)
}



//返回跳转
let left = document.querySelector('.header .left')
left.onclick = function () {
  window.location.href = "../public/firstPage.html";
}